/*接收消息*/
function send(headSrc,str,time){
	var html="<div class='send'><div class=\"time\">"+ time +"</div><div class='msg'><img src="+headSrc+" />"+
	"<p><i class='msg_input'></i>"+str+"</p></div></div>";
	upView(html);
}
/*发送消息*/
function show(headSrc,str,time){
	var html="<div class='show'><div class=\"time\">"+ time +"</div><div class='msg'>"+
	"<p><i class='msg_input'></i>"+str+"</p></div></div>";
	upView(html);
}
/*更新视图*/
function upView(html){
	$('.message').append(html);
	$('body').animate({scrollTop:$('.message').outerHeight()-window.innerHeight},200)
}

$(function(){
    //发送按钮的启用
	$('.footer').on('keyup','input',function(){
		if($(this).val().length>0){
			$(this).next().css('background','#114F8E').prop('disabled',true);
		
		}else{
			$(this).next().css('background','#ddd').prop('disabled',false);
        }
    });

    // 调用方法  循环请求信息
    var user = JSON.parse(sessionStorage.getItem('user'));  //用户
    var img = "";
    test();


    // 发送按钮的点击事件
    $('.footer p').click(function(){
        var dateNow = new Date();
        var str = $('.footer input').val();
        $.post('/messages',{'user.id':user.id,'target.id':friendId,'content.content':str,type:1},function (data) {
            if(data.success){
                show(img,str,dateNow);
                $('.footer input').val('');
            };
        });
    });





    function test(){

        //web socket
        var websocket = null;
        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            websocket = new WebSocket("ws://192.168.43.240:9999/ws/chatServer/"+ friendId +"/"+ user.id +"/"+ 1);
            //连接成功建立的回调方法
            websocket.onopen = function () {
                websocket.send("客户端链接成功");
            };
            //接收到消息的回调方法
            websocket.onmessage = function (event) {
                setMessageInnerHTML(event.data);
            };
            //连接发生错误的回调方法
            websocket.onerror = function () {
                alert("WebSocket连接发生错误");
            };
            //连接关闭的回调方法
            websocket.onclose = function () {
                alert("WebSocket连接关闭");
            };
            //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
            window.onbeforeunload = function () {
                closeWebSocket();
            }
        }
        else {
            alert('当前浏览器 Not support websocket')
        }

        //将消息显示在网页上
        function setMessageInnerHTML(data) {
            console.log(data);
            var info = JSON.parse(data);
            $.each(info.list,function (index, item) {
                send(item.headSrc,item.str,item.time);
            })
            /*var bitcoin = eval("("+innerHTML+")");
            document.getElementById('price').innerHTML = bitcoin.price;
            document.getElementById('total').innerHTML = bitcoin.total;*/
        }
        //关闭WebSocket连接
        function closeWebSocket() {
            websocket.close();
        }


        /*setInterval(function () {
            console.log(1);
            $.get('/messages/dialogs',{userId:friendId,targetId:user.id,type:1},function (data) {
                if (data){
                    console.log(data);
                    $.each(data,function (index, item) {
                        var headSrc = item.user.headImgUrl;
                        var str = item.content.content;
                        var time = item.creatdate;
                        img = item.target.headImgUrl;
                        send(headSrc,str,time);
                    })
                }
            })
            $.ajax({
                type: "PUT",
                url: "/messages/batchMarkread",
                data: {"userId":friendId,"targetId":user.id,type:1},
                success: function(data){

                }
            });
        },1000);*/

    }
})


